package com.trendata.aliyun;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.trendata.util.HttpClientUtil;
import com.trendata.util.ResultDO;
import com.trendata.util.TimeUtil;

public class AliyunOSSClient {

	private static String ACCESS_KEY_ID = "29rUUsTRIXAJs6nb";
	private static String ACCESS_KEY_SECRET = "eOPVTsqlwYnTA8kEeIXz0iH4D9wKsT";
	private static String BUCKET_NAME = "trendata";
	private static String BASE_RESOURCE_PATH = "/" + BUCKET_NAME + "/"; // 请求资源根路径
	private static final String charset = "UTF-8"; // 默认使用编码
	/**
	 * CDN地址
	 */
	public static final String CDN_NAME = "http://alicdn.trend-data.cn/";

	/**
	 * 
	 * @param key
	 * @param inputStream
	 * @param objectMetadata
	 * @return
	 */
	public static ResultDO<String> putObject(String key, InputStream inputStream, ObjectMetadata objectMetadata) {
		ResultDO<String> resultDO = new ResultDO<String>();
		if (StringUtils.isEmpty(key)) {
			resultDO.setErrMsg("上传图片至阿里云时key不能为空");
			return resultDO;
		}
		OSSClient client = new OSSClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		try {
			client.putObject(BUCKET_NAME, key, inputStream, objectMetadata);
		} catch (Exception e) {
			e.printStackTrace();
			resultDO.setErrMsg("上传图片时出现异常：" + e.getMessage());
		}

		// 拼访问地址
		String url = AliyunOSSClient.CDN_NAME + key;
		resultDO.setModule(url);
		resultDO.setSuccess(true);
		return resultDO;
	}

	/**
	 * 删除Object
	 * 
	 * @param key
	 *            在oss里存储的唯一key
	 */
	public static void deleteObject(String key) {
		if (StringUtils.isEmpty(key)) {
			return;
		}
		OSSClient client = new OSSClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		client.deleteObject(BUCKET_NAME, key);
	}

	/**
	 * 获得签名(简易版，忽视了2个参数——md5、header)
	 * 
	 * @param method
	 *            http动作（PUT,DELETE,POST,GET...）
	 * @param contentType
	 *            请求内容的类型，可为null
	 * @param date
	 *            此次操作的时间，且必须为 HTTP1.1 中支持的 GMT 格式
	 * @param resourcePath
	 *            用户想要访问的 OSS 资源
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 */
	private static String computeSignature(String method, String contentType, String date, String resourcePath) throws InvalidKeyException,
			NoSuchAlgorithmException, UnsupportedEncodingException {

		if (contentType == null) {
			contentType = "";
		}

		resourcePath = resourcePath.replaceAll("//", "/");

		StringBuffer data = new StringBuffer(method.toUpperCase()).append("\n\n").append(contentType).append("\n").append(date)
				.append("\n").append(resourcePath);

		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(new SecretKeySpec(ACCESS_KEY_SECRET.getBytes(charset), "HmacSHA1"));

		return "OSS " + ACCESS_KEY_ID + ":" + new String(Base64.encodeBase64(mac.doFinal(data.toString().getBytes(charset))));
	}

	/**
	 * 调用图片处理服务，并返回处理好的图片的流
	 * 
	 * @param key
	 *            文件路径
	 * @param transform
	 *            转化字符
	 * @return
	 * @throws IOException
	 * @throws InvalidKeyException
	 * @throws NoSuchAlgorithmException
	 */
	public static HttpURLConnection callImgService(String key, String transform) throws IOException, InvalidKeyException,
			NoSuchAlgorithmException {
		key += "@" + transform;

		String date = TimeUtil.getRfc822DateFormat(new Date());

		HttpURLConnection httpURLConnection = HttpClientUtil.getHttpURLConnection("http://imgop.trend-data.cn/" + key);
		httpURLConnection.setRequestProperty("Date", date);
		httpURLConnection.setRequestProperty("Authorization", computeSignature("GET", null, date, BASE_RESOURCE_PATH + key));

		httpURLConnection.connect();
		return httpURLConnection;
	}

	public static void main(String[] args) throws IOException, InvalidKeyException, NoSuchAlgorithmException {
		String transform =  "100w_100h_1e_1c";
		ObjectMetadata objectMetadata = new ObjectMetadata();
		HttpURLConnection httpURLConnection = null;
		for (int i = 2; i <=47; i++) {
			String key = "snapshot/shops/100000/publicImages/2015/03/25/" + i + ".jpg";
			String cutKey = "snapshot/shops/100000/publicImages/2015/03/25/" + i + "_cut.jpg";
			httpURLConnection = callImgService(key, transform);
			objectMetadata.setContentLength(httpURLConnection.getContentLengthLong());
			objectMetadata.setContentType(httpURLConnection.getContentType());
			objectMetadata.setContentEncoding("utf-8");
			AliyunOSSClient.putObject(cutKey, httpURLConnection.getInputStream(), objectMetadata);
			System.out.println(i+"ok");
		}
		
	}
}
